﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using AnalisisDeRiesgos.Dal;

namespace AnalisisDeRiesgos.Models.Action
{
    public class DetailsActionModel
    {
        public int ActionId { get; set; }
        public int DangerId { get; set; }
        public string Type { get; set; }
        public string DescriptionAction { get; set; }
        public string Responsible { get; set; }
        public string ProgrammedDate { get; set; }
        public string ExecutionDate { get; set; }
        public string Status { get; set; }

        private riskanalysisEntities entities = new riskanalysisEntities();

        public DetailsActionModel()
        { }

        public DetailsActionModel(int actionId)
        {
            var query = from a in entities.actions
                        where a.actionId == actionId
                        select new
                        {
                            ActionId = a.actionId,
                            DangerId = a.dangerId,
                            Description = a.description,                            
                            Type = a.actiontype.name,                            
                            Responsible = a.user.firstName + " " + a.user.lastName + " " + a.user.secondLastName,
                            ProgrammedDate = a.programedDate,
                            ExecutionDate = a.executionDate,
                            Status = a.status
                        };

            var theAction = query.FirstOrDefault();

            if (theAction == null)
                throw new DetailsActionException("La accion especificada no existe");
            
            string executionDate = theAction.ExecutionDate.ToString("d", Utils.culture);

            executionDate = executionDate.Equals("01/01/2000") ? "Sin fecha" : executionDate;
            ActionId = theAction.ActionId;
            DangerId = theAction.DangerId;
            DescriptionAction = theAction.Description;
            Type = theAction.Type;
            Responsible = theAction.Responsible;
            ExecutionDate = executionDate;
            ProgrammedDate = theAction.ProgrammedDate.ToString("d", Utils.culture);
            Status = theAction.Status.ToString();
        }

        public void DeleteAction()
        {
            var query = from a in entities.actions
                        where a.actionId == ActionId
                        select a;
            if (query.Count() <= 0)
                throw new DetailsActionException("La accion especificada no fue encontrada");

            entities.actions.DeleteObject(query.First());
            entities.SaveChanges();
        }
    }
}